package task

import (
	"errors"
	"k8s-admin/global"
	"k8s-admin/models"
	"k8s-admin/utils"
)

type InterfaceTasks interface {
	Create(req *models.TaskReq) error
	List() (*models.TaskRes, error)
	HistoryLists() (*models.TaskRes, error)
	Delete(TaskNumber string) error
	Update(TasksNumber string, req *models.TaskReq) error
}

type TasksInfo struct {
}

func NewInterfaceTasks() InterfaceTasks {
	return &TasksInfo{}
}

func (t *TasksInfo) Create(req *models.TaskReq) error {
	taskNumber := utils.GemSnowFlask(req.TaskName)
	err := global.GORM.Create(&models.Task{
		TaskNumber: taskNumber,
		TaskName:   req.TaskName,
		Module:     req.Module,
		HostsIp:    req.HostsIp,
		ShellExec:  req.ShellExec,
	}).Error
	if err != nil {
		return err
	} else {
		return nil
	}
}

func (t *TasksInfo) List() (*models.TaskRes, error) {
	tasksList := []models.Task{}
	tx := global.GORM.Model(&models.Task{}).Find(&tasksList)
	if tx.Error != nil {
		return nil, tx.Error
	} else if tx.RowsAffected == 0 {
		return nil, errors.New("占无数据")
	} else {
		return &models.TaskRes{
			Items: tasksList,
			Total: len(tasksList),
		}, nil
	}
}

func (t *TasksInfo) HistoryLists() (*models.TaskRes, error) {
	tasksLists := []models.Task{}
	tx := global.GORM.Model(&models.Task{}).Where("status=1").Find(&tasksLists)
	if tx.Error != nil {
		return nil, tx.Error
	} else if tx.RowsAffected == 0 {
		return nil, errors.New("占无数据")
	} else {
		return &models.TaskRes{
			Items: tasksLists,
			Total: len(tasksLists),
		}, nil
	}
}

func (t *TasksInfo) Delete(TaskNumber string) error {
	tx := global.GORM.Where("task_number=?", TaskNumber).Delete(&models.Task{})
	if tx.Error != nil {
		return tx.Error
	} else if tx.RowsAffected == 0 {
		return errors.New("删除失败，没有该数据")
	} else {
		return nil
	}
}

func (t *TasksInfo) Update(TasksNumber string, req *models.TaskReq) error {
	tx := global.GORM.Model(&models.Task{}).Where("task_number=?", TasksNumber).Updates(&models.Task{
		TaskName:  req.TaskName,
		Module:    req.Module,
		ShellExec: req.ShellExec,
		HostsIp:   req.HostsIp,
	})
	if tx.Error != nil {
		return tx.Error
	} else if tx.RowsAffected == 0 {
		return errors.New("更新失败，没有该数据")
	} else {
		return nil
	}
}

